﻿using System;
using System.IO;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MyLib.Tests
{
   [TestClass]
   public static class AssemblyStartStop
   {
      private static Process mongoDBProcess;

      [AssemblyInitialize]
      public static void Startup(TestContext context)
      {
         var basePath = AppDomain.CurrentDomain.BaseDirectory;
         var exePath = basePath + "\\..\\..\\mongodb\\bin\\mongod.exe";
         var dbPath = "mongoTestDB";

         if (!Directory.Exists(dbPath)) Directory.CreateDirectory(dbPath);

         var pstart = new ProcessStartInfo(exePath, "--dbpath " + dbPath)
         {
            CreateNoWindow = true,
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true
         };

         mongoDBProcess = Process.Start(pstart);
         mongoDBProcess.WaitForExit();

         string output = mongoDBProcess.StandardOutput.ReadToEnd();
         string error = mongoDBProcess.StandardError.ReadToEnd();

         var ExitCode = mongoDBProcess.ExitCode;

         Debug.WriteLine("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
         Debug.WriteLine("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
         Debug.WriteLine("ExitCode: " + ExitCode.ToString(), "ExecuteCommand");
         mongoDBProcess.Close();
      }

      [AssemblyCleanup]
      public static void Cleanup()
      {
         mongoDBProcess.Close();
         //TODO: Remove the MongoDB test database files.
      }
   }
}
